<?php

class Storage_Adapter_Rackspace extends Storage_Adapter
{
	protected $_basePath;

	protected $_baseUrl;

	protected $_key = '';

	protected $_bucket = '';

	protected $_container = NULL;

	protected $_connection = NULL;

	protected $_ssl = FALSE;

	public function __construct($id, $config)
	{
		$this -> _id = $id;
		$this -> _username = $config['username'];
		$this -> _key = $config['key'];
		$this -> _bucket = $config['bucket'];
		$this -> _baseUrl = rtrim($config['baseUrl'], '/') . '/';
		$this -> _basePath = rtrim($this -> _bucket . '/' . $path, '/') . '/';
	}

	function getContainer()
	{
		if (null == $this -> _container)
		{
			require_once dirname(__FILE__) . '/libs/cloudfiles.php';
			$auth = new CF_Authentication($this -> _username, $this -> _key);
			$auth -> authenticate();
			$this -> _connection = new CF_Connection($auth);
			$this -> _container = $this -> _connection -> get_container($this -> _bucket);
		}
		return $this -> _container;
	}

	function get($relative_path, $local_file, $force = TRUE)
	{
		self::_makeLocalDir(dirname($local_file));

		$path = $this -> mapPath($relative_path);

		if (!$this -> getContainer()->create_object($path) -> save_to_filename($local_file))
		{
			if ($force)
			{
				throw new Storage_Exception('could not get {from} to s3 {to}', array(
					'{from}' => $path,
					'{to}' => $local_file
				));
			}
			return FALSE;
		}
		return TRUE;

	}

	/**
	 *
	 */
	public function put($relative_path, $local_file, $force = TRUE)
	{
		$path = $this->mapPath($relative_path);
		
		$object = $this->getContainer()->create_object($path);

		if (!$object->load_from_filename($local_file))
		{
			if ($force)
			{
				throw new Storage_Exception('could not put {from} to s3 {to}', array(
					'{from}' => $local_file,
					'{to}' => $path
				));
			}
			return FALSE;
		}
		return TRUE;
	}

	function getContents($relative_path, $force = TRUE)
	{
		$path = $this -> mapPath($relative_path);

		$data =  $this -> getContainer() -> create_object($path)->read();

		if ($data === FALSE)
		{
			if ($force)
			{
				throw new Storage_Exception('File {file} does not exists!', array('{file}' => $path));
			}
		}
		return $data;
	}

	function putContents($relative_path, $data, $force = TRUE)
	{
		$path = $this -> mapPath($relative_path);

		if (!$this -> getContainer() ->create_object($path)->write($data));
		{
			if ($force)
			{
				throw new Storage_Exception('could not put data to s3 {to}', array('{to}' => $path));
			}
			return FALSE;
		}

		return TRUE;
	}

	function delete($relative_path, $force = TRUE)
	{
		$path = $this -> mapPath($relative_path);

		if (!$this -> getContainer() -> delete_object($path))
		{
			if ($force)
			{
				throw new Storage_Exception('Rackspace: {file} could not be removed!', array('{file}' => $path));
				return FALSE;
			}
		}
		return TRUE;
	}
}
